// @ts-nocheck
import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import '@/components/dhtmlx/gantt/codebase/dhtmlxgantt.css?v=7.1.12';
import '@/components/dhtmlx/assets/iconfont/iconfont.css';
import '@/components/dhtmlx/gantt/codebase/dhtmlxgantt.js?v=7.0.7';
import '@/components/dhtmlx/gantt/codebase/locale/locale_cn.js';
import '@/components/dhtmlx/gantt/codebase/ext/dhtmlxgantt_tooltip.js?v=7.0.7';
import '@/components/dhtmlx/assets/iconfont/iconfont.js';
import $ from 'jquery';
import moment from "moment";
import { Radio } from "antd";
import { svgPath } from "@/types/constant";
import language from "@/locales/zh_cn";

interface Props {
  elements: any[];
  links: [];
  onResourceClick: (resource_id: string) => void;
}

const ResourceDispatch = forwardRef(({
  elements,
  links,
  onResourceClick,
}: Props, ref) => {
  const [model, setModel] = useState('hour');
  const ganttRef = useRef(null);
  const ganttInstance = useRef(null);

  const initGantt = () => {
    if (!ganttRef.current) return;

    try {
      // 清理旧的实例
      if (ganttInstance.current) {
        ganttInstance.current.clearAll();
        ganttInstance.current.destructor();
      }

      // 创建新实例
      ganttInstance.current = Gantt.getGanttInstance();
      if (!ganttInstance.current) {
        console.error('Failed to get gantt instance');
        return;
      }

      // 配置 gantt
      ganttInstance.current.config.date_format = "%Y-%m-%d %H:%i:%s";
      ganttInstance.current.config.drag_move = false;
      ganttInstance.current.config.drag_multiple = false;
      ganttInstance.current.config.drag_progress = false;
      ganttInstance.current.config.drag_resize = false;
      ganttInstance.current.config.drag_project = false;
      ganttInstance.current.config.show_links = false;
      ganttInstance.current.config.fit_tasks = true;

      // 配置列
      ganttInstance.current.config.columns = [
        { name: 'text', label: '资源', width: 160, tree: false, resize: true },
        {
          name: 'is_aps', label: '', align: 'center', width: 30,
          template: function(item) {
            return item.is_aps ? `<img src="${svgPath}star.svg" width="20" style="position:relative;top:10px;" />` : '';
          }
        },
      ];

      // 配置提示
      ganttInstance.current.templates.tooltip_text = function (start, end, item) {
        if (item.capacity && item.mbom_num) {
          return `<b>${language.work_order_num}：</b>` + item.work_order_num  +
            `<br/><b>${language.batch_num}：</b>` + item.batch_order_num +
            `<br/><b>${language.product_name}：</b>` + item.product_name +
            `<br/><b>${language.mbom_num}：</b>` + item.mbom_num +
            `<br/><b>${language.process_num}：</b>` + item.process_num +
            (item.work_user_name ? (`<br/><b>派工人员：</b>` + item.work_user_name) : '') +
            (item.work_station_num ? (`<br/><b>派工工位：</b>` + item.work_station_num) : '') +
            (item.work_device_num ?(`<br/><b>派工设备：</b>` + item.work_device_num) : '') +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        } else if (item.capacity == 2) {
          return`<b>设备停机</b>` +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        } else if (item.capacity == 4) {
          return`<b>请假/休假</b>` +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        }
      }

      // 配置缩放
      const zoomConfig = {
        levels: [
          {
            name: 'hour',
            scale_height: 50,
            min_column_width: 50,
            scales: [
              { unit: 'day', step: 1, format: '%m/%d' },
              { unit: 'hour', step: 1, format: '%H:%i' }
            ]
          },
          {
            name: 'day',
            scale_height: 27,
            min_column_width: 80,
            scales: [
              { unit: 'day', step: 1, format: '%m/%d' }
            ]
          },
          {
            name: 'week',
            scale_height: 50,
            min_column_width: 50,
            scales: [
              {
                unit: 'week', step: 1, format: function (date) {
                  let dateToStr = ganttInstance.current.date.date_to_str('%d %M');
                  let endDate = ganttInstance.current.date.add(date, -6, 'day');
                  let weekNum = ganttInstance.current.date.date_to_str('%W')(date);
                  return '#' + weekNum + ', ' + dateToStr(date) + ' - ' + dateToStr(endDate);
                }
              },
              { unit: 'day', step: 1, format: '%j %D' }
            ]
          },
          {
            name: 'month',
            scale_height: 50,
            min_column_width: 120,
            scales: [
              { unit: 'month', format: '%Y %F' },
              { unit: 'week', format: 'Week #%W' }
            ]
          },
          {
            name: 'quarter',
            scale_height: 50,
            min_column_width: 90,
            scales: [
              { unit: 'month', step: 1, format: '%M' },
              {
                unit: 'quarter', step: 1, format: function (date) {
                  let dateToStr = ganttInstance.current.date.date_to_str('%M');
                  let endDate = ganttInstance.current.date.add(ganttInstance.current.date.add(date, 3, 'month'), -1, 'day');
                  return dateToStr(date) + ' - ' + dateToStr(endDate);
                }
              }
            ]
          },
          {
            name: 'year',
            scale_height: 50,
            min_column_width: 30,
            scales: [
              { unit: 'year', step: 1, format: '%Y' }
            ]
          }
        ]
      };

      ganttInstance.current.ext.zoom.init(zoomConfig);
      ganttInstance.current.ext.zoom.setLevel(model);

      // 初始化
      ganttInstance.current.init(ganttRef.current);

      // 配置点击事件
      ganttInstance.current.attachEvent("onTaskClick", function(id, e) {
        const task = ganttInstance.current.getTask(id);
        if (task && task.type === 'project') {
          onResourceClick(id);
        }
        return false;
      });

      ganttInstance.current.attachEvent("onTaskDblClick", function() {
        return false;
      });

      // 加载数据
      if (elements && elements.length > 0) {
        ganttInstance.current.parse({
          data: elements,
          links: links || [],
        });
      }

      // 设置事件
      setTipEvent();

    } catch (e) {
      console.error('Error initializing gantt:', e);
    }
  }

  useImperativeHandle(ref, () => ({
    init: () => {
      initGantt();
    },
    reInit: () => {
      initGantt();
    }
  }));

  useEffect(() => {
    if (ganttInstance.current && elements && elements.length > 0) {
      try {
        const currentScrollPosition = ganttInstance.current.getScrollState();
        ganttInstance.current.clearAll();
        ganttInstance.current.parse({
          data: elements,
          links: links || [],
        });
        if (currentScrollPosition) {
          ganttInstance.current.scrollTo(currentScrollPosition.x, currentScrollPosition.y);
        }
      } catch (e) {
        console.error('Error updating gantt data:', e);
      }
    }
  }, [elements, links]);

  const setTipEvent = () => {
    $('#dispatch-gantt').off('mouseleave');
    $('#dispatch-gantt').on('mouseleave', function() {
      $('.gantt_tooltip').remove();
    });
  }

  const onModelChange = (e) => {
    setModel(e.target.value);
    if (ganttInstance.current?.ext?.zoom) {
      try {
        ganttInstance.current.ext.zoom.setLevel(e.target.value);
      } catch (e) {
        console.error('Error changing zoom level:', e);
      }
    }
  }

  return (
    <div className="h-full flex flex-col">
      <div className="flex justify-end p-2">
        <Radio.Group value={model} onChange={onModelChange}>
          <Radio.Button value="hour">小时</Radio.Button>
          <Radio.Button value="day">天</Radio.Button>
          <Radio.Button value="week">周</Radio.Button>
          <Radio.Button value="month">月</Radio.Button>
          <Radio.Button value="quarter">季度</Radio.Button>
          <Radio.Button value="year">年</Radio.Button>
        </Radio.Group>
      </div>
      <div ref={ganttRef} style={{height: '100%'}} className="flex-1" id="dispatch-gantt"></div>
    </div>
  );
});

export default ResourceDispatch;